package com.cskaoyan.gateway.controller.shopping;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.shopping.ICartService;
import com.mall.shopping.constants.ShoppingRetCode;
import com.mall.shopping.dto.*;
import com.mall.user.intercepter.TokenIntercepter;
import io.swagger.annotations.Api;
import lombok.extern.slf4j.Slf4j;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;

/**
 * @Name : CartsController.java
 * @Time : 2021/8/26 16:24
 * @Author : creamycandy
 * @Software : IntelliJ IDEA
 */
@Slf4j
@RestController
@RequestMapping("/shopping")
@Api(tags = "CartsController", description = "购物车控制层")
public class CartsController {
    @Reference(timeout = 20000, retries = 0, check = false)
    ICartService iCartService;

    @GetMapping("/carts")
    public ResponseData getCarts(HttpServletRequest servletRequest) {
        //从TokenInterceptor设置的request域中取出当前登录的userId
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        long userId = Long.parseLong(object.get("uid").toString());
        CartListByIdRequest request = new CartListByIdRequest();
        request.setUserId(userId);
        CartListByIdResponse cartListById = iCartService.getCartListById(request);
        if(ShoppingRetCode.SUCCESS.getCode().equals(cartListById.getCode())){
            //成功
            return new ResponseUtil().setData(cartListById.getCartProductDtos());
        }
        //失败
        return new ResponseUtil().setErrorMsg(cartListById.getMsg());

    }


    @PostMapping("carts")
    public ResponseData addCarts(@RequestBody AddCartRequest request,
                                 HttpServletRequest servletRequest){
        //从TokenInterceptor设置的request域中取出当前登录的userId
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        long tokenUserId = Long.parseLong(object.get("uid").toString());
        if(!request.getUserId().equals(tokenUserId)){
            return new ResponseUtil().setErrorMsg("非法侵入！");
        }
        AddCartResponse response = iCartService.addToCart(request);
        if(ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @PutMapping("carts")
    public ResponseData updateCarts(@RequestBody UpdateCartNumRequest request,
                                    HttpServletRequest servletRequest){
        //从TokenInterceptor设置的request域中取出当前登录的userId
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        long tokenUserId = Long.parseLong(object.get("uid").toString());
        if(!request.getUserId().equals(tokenUserId)){
            return new ResponseUtil().setErrorMsg("非法侵入！");
        }
        UpdateCartNumResponse response = iCartService.updateCartNum(request);
        if(ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @DeleteMapping("carts/{uid}/{pid}")
    public ResponseData deleteCarts(@PathVariable("uid") Integer uid,
                                    @PathVariable("pid") Integer pid,
                                    HttpServletRequest servletRequest){
        //从TokenInterceptor设置的request域中取出当前登录的userId
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        long tokenUserId = Long.parseLong(object.get("uid").toString());

        DeleteCartItemRequest request = new DeleteCartItemRequest();
        request.setUserId(Long.valueOf(uid));
        request.setItemId(Long.valueOf(pid));
        if(!request.getUserId().equals(tokenUserId)){
            return new ResponseUtil().setErrorMsg("非法侵入！");
        }
        DeleteCartItemResponse response = iCartService.deleteCartItem(request);
        if(ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @DeleteMapping("/items/{uid}")
    public ResponseData deleteCheckedCarts(@PathVariable("uid") Integer uid,
                                           HttpServletRequest servletRequest){
        //从TokenInterceptor设置的request域中取出当前登录的userId
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        long tokenUserId = Long.parseLong(object.get("uid").toString());

        DeleteCheckedItemRequest request = new DeleteCheckedItemRequest();
        request.setUserId(Long.valueOf(uid));
        if(!request.getUserId().equals(tokenUserId)){
            return new ResponseUtil().setErrorMsg("非法侵入！");
        }
        DeleteCheckedItemResposne response = iCartService.deleteCheckedItem(request);
        if(ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }

    @PutMapping("items")
    public ResponseData checkAllCarts(@RequestBody CheckAllItemRequest request,
                                      HttpServletRequest servletRequest){
        String userInfo = (String) servletRequest.getAttribute(TokenIntercepter.USER_INFO_KEY);
        JSONObject object = JSON.parseObject(userInfo);
        long tokenUserId = Long.parseLong(object.get("uid").toString());
        if(!request.getUserId().equals(tokenUserId)){
            return new ResponseUtil().setErrorMsg("非法侵入！");
        }
        CheckAllItemResponse response = iCartService.checkAllCartItem(request);
        if(ShoppingRetCode.SUCCESS.getCode().equals(response.getCode())){
            return new ResponseUtil().setData(null);
        }
        return new ResponseUtil().setErrorMsg(response.getMsg());
    }
}
